package articles_api

import (
	"context"
	"encoding/json"
	"gin_study_blog/common"
	"gin_study_blog/common/http"
	"gin_study_blog/models"
	"github.com/gin-gonic/gin"
	"github.com/olivere/elastic/v7"
	"time"
)

type CalenderResponse struct {
	Date  string `json:"date"`
	Count int    `json:"count"`
}

type BucketsType struct {
	Buckets []struct {
		KeyAsString string `json:"key_as_string"`
		Key         int64  `json:"key"`
		DocCount    int    `json:"doc_count"`
	} `json:"buckets"`
}

var DateCount = map[string]int{}

func (ArticlesApi) ArticleViewCalender(c *gin.Context) {
	// 时间聚合
	agg := elastic.NewDateHistogramAggregation().Field("created_at").CalendarInterval("day")

	// 时间段搜索
	// 从今天开始, 到昨年
	now := time.Now()
	yearAge := now.AddDate(-1, 0, 0)
	//yearAge := now.Add(-240 * time.Hour)
	format := "2006-01-02 15:04:05"

	// gte 大于 lte 小于
	query := elastic.NewRangeQuery("created_at").
		Gte(yearAge.Format(format)).
		Lte(now.Format(format))

	result, err := common.EsClient.Search(models.ArticleModel{}.Index()).
		Query(query).
		Aggregation("calender", agg).
		Size(0).Do(context.Background())
	if err != nil {
		common.Log.Error(err)
		http.FailWithMessage("查询失败", c)
		return
	}

	resList := make([]CalenderResponse, 0)

	var data BucketsType
	_ = json.Unmarshal(result.Aggregations["calender"], &data)
	for _, bucket := range data.Buckets {
		Time, _ := time.Parse(format, bucket.KeyAsString)
		DateCount[Time.Format("2006-01-02")] = bucket.DocCount
		//resList = append(resList, CalenderResponse{
		//	Date:  Time.Format("2006-01-02"),
		//	Count: bucket.DocCount,
		//})
	}

	// 计算两个时间差值
	// now.Sub(yearAge).Hours() 获取差值所有小时 / 24 获取天数
	days := int(now.Sub(yearAge).Hours() / 24)
	for i := 0; i <= days; i++ {
		day := yearAge.AddDate(0, 0, i).Format("2006-01-02")
		count, _ := DateCount[day]

		resList = append(resList, CalenderResponse{
			Date:  day,
			Count: count,
		})
	}

	http.IsOkWithData(resList, c)
}
